package com.liruo.docker.service1;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

/**
 * @Author:liruo
 * @Date:2023-05-31-22:48:44
 * @Desc
 */
@RestController
public class Service1Controller {
    @GetMapping("/service1")
    public String service1() {
        return "service1-----";
    }

    @Value("${service2Host: service2}")
    private String service2Host;

    @Value("${service2Port: 8020}")
    private String service2Port;

    @GetMapping("/access-service2")
    public String accessService2() {
        try {
            URL url = new URL("http://" + service2Host + ":" + service2Port + "/service2");
            URLConnection urlConnection = url.openConnection();
            urlConnection.connect();
            InputStream inputStream = urlConnection.getInputStream();
            String contentEncoding = urlConnection.getContentEncoding();
            if (!StringUtils.hasText(contentEncoding)) {
                contentEncoding = urlConnection.getContentType();
                if (StringUtils.hasText(contentEncoding) && contentEncoding.contains("charset")) {
                    contentEncoding = contentEncoding.substring(contentEncoding.indexOf("charset=") + "charset=".length());
                } else {
                    contentEncoding = StandardCharsets.UTF_8.name();
                }
            }
            return new String(inputStream.readAllBytes(), contentEncoding);
        } catch (Exception e) {
            return "err= " + e.getMessage();
        }
    }
}
